package com.codeyourlife.service.impl;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Date;
import java.util.Properties;
import java.util.Random;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

import com.codeyourlife.dao.EmailverifyDao;
import com.codeyourlife.entity.EmailVerify;
import com.codeyourlife.service.EmailVerifyService;

@Service("emailVerifyService")
public class EmailVerifyServiceImpl implements EmailVerifyService {
	
	@Autowired
	private EmailverifyDao emailDao;
	
	private static Session session;
	private static Properties props = new Properties();
	private static final String HOST = "smtp.sina.com";
	private static int PORT = 25;
	private static final String isAUTH = "true";
	private static final String FROM = "miclewang813@sina.com";

	private static final String USERNAME = "miclewang813@sina.com";
	private static final String PASSWORD = "sinaMICLE023";

	private static final String TIMEOUT = "25000";
	private static final String DEBUG = "true";

	// initial session
	static {
		props.put("mail.smtp.host", HOST);
		props.put("mail.smtp.port", PORT);
		props.put("mail.smtp.auth", isAUTH);
		props.put("fromer", FROM);
		props.put("username", USERNAME);
		props.put("password", PASSWORD);
		props.put("mail.smtp.timeout", TIMEOUT);
		props.put("mail.debug", DEBUG);
		session = Session.getInstance(props, new Authenticator() {
			@Override
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(USERNAME, PASSWORD);
			}
		});
	}

	// send email only with text;
	public void sendTextEmail(String to, String subject, String content)
			throws FileNotFoundException, IOException, MessagingException {

		Message message = new MimeMessage(session);
		message.setFrom(new InternetAddress(FROM));
		message.setRecipient(RecipientType.TO, new InternetAddress(to));
		message.setSubject(subject);
		message.setText(content);
		message.setSentDate(new Date());
		Transport.send(message);
	}

	// send html email;
	public void sendHtmlEmail(String to, String subject, String htmlConent)
			throws FileNotFoundException, IOException, MessagingException {

		Message message = new MimeMessage(session);
		message.setFrom(new InternetAddress(FROM));
		message.setRecipient(RecipientType.TO, new InternetAddress(to));
		message.setSubject(subject);
		message.setSentDate(new Date());

		Multipart multi = new MimeMultipart();
		BodyPart html = new MimeBodyPart();
		html.setContent(htmlConent, "text/html; charset=utf-8");
		multi.addBodyPart(html);
		message.setContent(multi);
		Transport.send(message);
	}

	// send mail with file.
	public void sendFileEmail(String to, String subject, String htmlConent, File attachment)
			throws FileNotFoundException, IOException, MessagingException {
		Message message = new MimeMessage(session);
		String fromer = props.getProperty("fromer");
		message.setFrom(new InternetAddress(fromer));
		message.setRecipient(RecipientType.TO, new InternetAddress(to));
		message.setSubject(subject);
		message.setSentDate(new Date());
		// 向multipart对象中添加邮件的各个部分内容，包括文本内容和附件
		Multipart multipart = new MimeMultipart();
		// 添加邮件正文
		BodyPart contentPart = new MimeBodyPart();
		contentPart.setContent(htmlConent, "text/html;charset=UTF-8");
		multipart.addBodyPart(contentPart);
		// 添加附件的内容
		if (attachment != null) {
			BodyPart attachmentBodyPart = new MimeBodyPart();
			DataSource source = new FileDataSource(attachment);
			attachmentBodyPart.setDataHandler(new DataHandler(source));
			// MimeUtility.encodeWord可以避免文件名乱码
			attachmentBodyPart.setFileName(MimeUtility.encodeWord(attachment.getName()));
			multipart.addBodyPart(attachmentBodyPart);
		}
		message.setContent(multipart);
		Transport.send(message);
	}

	// get random code;
	public String getUUID(int len) {
		String chars = "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789";
		int max = chars.length();
		int min = 0;
		Random random = new Random();

		String uid = "";
		for (int i = 0; i < len; i++) {
			int s = random.nextInt(max) % (max - min + 1) + min;
			uid += chars.charAt(s);
		}
		return uid;
	}

	// add EmailVerifycode
	public void setEmailverifyDao(EmailverifyDao emailDao) {
		this.emailDao = emailDao;
	}
	
	public void addEmailVerifyCode(EmailVerify code) {
		emailDao.addRecord(code);
	}

	public EmailVerify findEmailVerifyByEmail(String email, String ask_type) {
		System.out.println(email+" emailservice "+ask_type);
		try{
			return emailDao.getEmailVerifyByEmail(email, ask_type);
		}catch(Exception e){
			System.out.println("EmailServiceImpl: "+e.getStackTrace());
		}
		return null;
	}

	public void delEmailVerifyCode(int id) {
		emailDao.delRecord(id);
	}



}